/**
 * 自定义循环队列
 *      tail == front  ,则表示队列为空
 *
 *      （tail+1）%capacity == front  ,表示队列已满
 * @param <T>
 */
public class LoopQueue<T> implements Queue<T> {

    private T[] data;
    private int front,tail;
    private int size;

    public LoopQueue(int capacity){
        //因为循环队列会浪费一个空间，所以要+1
        data = (T[]) new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue(){
        this(10);
    }

    //查看容量
    public int getCapacity(){
        return data.length - 1;
    }

    /**
     * 向循环队列中添加元素
     * @param t
     */
    @Override
    public void enqueue(T t) {
        if((tail + 1) % data.length == front){
            resize(getCapacity() * 2);
        }
        data[tail] = t;
        tail = (tail+1)%data.length;
        size++;
    }

    @Override
    public T dequeue() {
        if(isEmpty()){
            throw new IllegalArgumentException("Cannot dequeue from an Empty Queue");
        }

        T ret = data[front];
        data[front] = null;
        front = (front+1)%data.length;
        size--;
        //判断是否要缩容
        if(size < getCapacity()/2 && getCapacity() /2 != 0){
            resize(getCapacity() /2);
        }
        return ret;
    }

    /**
     * 扩容或缩容
     * @return
     */
    private void resize(int newCapacity){
        T[] newData = (T[]) new Object[newCapacity + 1];

        for(int i=0;i<size;i++){
            newData[i] = data[(front+i) % data.length];
        }

        data = newData;
        front = 0;
        tail=size;
    }

    @Override
    public T getFront() {
        return null;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        res.append("Queue: ");
        res.append(String.format("size=%d capacity=%d\n",getSize(),getCapacity()));
        res.append("front [");
        for(int i=front;i != tail;i=(i+1)%data.length){
            res.append(data[i]);
            if((i+1)%data.length != tail){
                res.append(", ");
            }
        }
        res.append("] tail");
        return res.toString();
    }

    public static void main(String[] args) {
        LoopQueue<Integer> queue = new LoopQueue<>();
        for (int i=0;i<10;i++){
            queue.enqueue(i);
            System.out.println(queue);

            if(i%3 == 2){
                queue.dequeue();
                System.out.println(queue);
            }
        }
    }
}
